package org.ecshop.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.ecshop.models.Region;
import org.ecshop.models.UserAddress;

import will.icecoffe.core.DataAccessException;
import will.icecoffe.core.SimpleDataAccessService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;



public class UserAddressController implements ModelDriven<Object> {

	private List<UserAddress> list = new ArrayList<UserAddress>();
	
	
	private int key;
	
	public int getKey() {
		return key;
	}

	public void setKey(int key) {
		this.key = key;
	}
	

	@Resource(name="DAS")
	private SimpleDataAccessService<UserAddress> das;
	
	@Resource(name="DAS")
	private SimpleDataAccessService<Region> rdas;
	
	
	public String index() throws DataAccessException {
		
		list = das.find("hql", "findUserAddressByUserId", key);
		
		Map<String, String> regionMap = (Map<String, String>) ActionContext.getContext().getApplication().get("regionMap");
		
		if(regionMap == null)
			regionMap = initRegionMap();
		
		for(UserAddress ua : list) {
			ua.setCountry(regionMap.get(ua.getCountry()));
			ua.setProvince(regionMap.get(ua.getProvince()));
			ua.setCity(regionMap.get(ua.getCity()));
			ua.setDistrict(regionMap.get(ua.getDistrict()));
		}
		
		return null;
		
	}
	
	private Map<String, String> initRegionMap() throws DataAccessException {
		
		List<Region> regionList = rdas.find("hql", "findAllRegion");
		Map<String, String> regionMap = new HashMap<String, String>();
		
		for(Region r : regionList) {
			regionMap.put(r.getRegionId().toString(), r.getRegionName());
		}
		
		ActionContext.getContext().getApplication().put("regionMap", regionMap);
		
		return regionMap;
	}
	
	@Override
	public Object getModel() {
		return list;
	}

}
